package com.lj.universalframework.utils

import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.os.Build
import android.text.TextUtils
import com.lj.universalframework.BuildConfig
import com.orhanobut.logger.Logger

/**
 * <p>文件名：Utils
 * <p>创建者：LJ
 * <p>创建日期：2020\10\15 0015 15:28
 * <p>描述：
 */
object Utils {
    /**
     * 检查网络状态
     */
    fun isNetworkConnected(context: Context): Boolean {
        var result = false
        val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            cm?.run {
                cm.getNetworkCapabilities(cm.activeNetwork)?.run {
                    result = when {
                        hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
                        hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
                        hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true
                        else -> false
                    }
                }
            }
        } else {
            cm?.run {
                cm.activeNetworkInfo?.run {
                    if (type == ConnectivityManager.TYPE_WIFI) {
                        result = true
                    } else if (type == ConnectivityManager.TYPE_MOBILE) {
                        result = true
                    }
                }
            }
        }
        return result
    }

    fun log(message: String) {
        if (!BuildConfig.DEBUG) return
        if (TextUtils.isEmpty(message)) return
        Logger.i(message)
    }

    fun logJson(message: String) {
        if (!BuildConfig.DEBUG) return
        if (TextUtils.isEmpty(message)) return
        Logger.json(message)
    }
}